/* eslint-disable consistent-return */
import React from 'react';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, Select, message, Modal, Row, Divider, Spin } from 'antd';
import { connect } from 'dva';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ loading }) => ({
  loading: loading.models.suppliermaintenance,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      suppId: null,
      bankList: [],
      areaList: [],
      fetching: false,
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
      vno: 1,
      saveAreaId: '',
    };

    this.columns = [
      {
        title: '城市',
        dataIndex: 'areaName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行',
        dataIndex: 'bankName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户行',
        dataIndex: 'openBank',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行账号',
        dataIndex: 'bankAcco',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户单位名称',
        dataIndex: 'accoHolderName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a onClick={e => this.update(e, record.bankAccoId)}>修改</a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { suppId, bankList } = this.props;
    const { nowPage, pageNum } = this.state;
    this.setState({ suppId, bankList }, () => {
      this.getList(nowPage, pageNum);
    });
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { suppId, dispatch } = this.props;
    this.setState({ loading: true });
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' BANK_ACCO_ID DESC',
    };
    const params = { suppId, pageArg };
    dispatch({
      type: 'suppliermaintenance/fetchBankList',
      payload: params,
      callback: res => {
        if (res.success && res.data.pageRecords) {
          const data = res.data.pageRecords;
          this.setState({ dataSource: data, cmTotal: res.data.totalCount, loading: false });
        } else {
          this.setState({ loading: false, cmTotal: 0, dataSource: [] });
          message.warning(`${res.message || '暂无数据！'}`);
        }
      },
    });
  };

  // 匹配字典
  matchDict = (list, id) => {
    let dict = null;
    list.forEach(item => {
      if (item.itemCode === id) {
        dict = item.itemName;
      }
    });
    return dict;
  };

  // 获取地区选项
  searchArea = value => {
    const { dispatch } = this.props;
    if (value) {
      this.setState({ areaList: [], fetching: true });
      dispatch({
        type: 'suppliermaintenance/queryNmArea',
        payload: { areaName: value },
        callback: res => {
          if (res.success && res.data.length) {
            this.setState({ areaList: res.data, fetching: false });
          }
        },
      });
    } else {
      this.setState({ areaList: [], fetching: false });
    }
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.bankAccoId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      title: '你确定要刪除此条银行账户信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        this.setState({ loading: true });
        dispatch({
          type: 'suppliermaintenance/deleteBankMul',
          payload: { list: rowKeys },
          callback: res => {
            this.setState({ loading: false });
            if (res.success) {
              const { cmTotal, nowPage, pageNum } = this.state;
              const selectedLen = selectedRowKeys.length;
              if (nowPage > 1 && (cmTotal % pageNum === selectedLen || pageNum === selectedLen)) {
                this.getList(nowPage - 1, pageNum);
                this.setState({ nowPage: nowPage - 1 });
              } else {
                this.getList(nowPage, pageNum);
              }
              this.setState({ selectedRowKeys: [] });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败！'}`);
            }
          },
        });
      },
    });
  };

  // 新增数据
  add = () => {
    const { form } = this.props;
    const { dataSource } = this.state;
    if (dataSource.length === 1) {
      message.warning(`该供应商下已维护银行账户，不能重复添加！`);
      return false;
    }
    this.handleModalVisible(true, true);
    form.resetFields();
  };

  // 修改数据
  update = (e, bankAccoId) => {
    e.preventDefault();
    const { suppId, form, dispatch } = this.props;
    const rowKeys = [];
    rowKeys.push(bankAccoId);
    this.setState({ selectedRowKeys: rowKeys, loading: true });
    if (suppId) {
      dispatch({
        type: 'suppliermaintenance/getBankInfo',
        payload: { bankAccoId },
        callback: res => {
          this.setState({ loading: false, suppId });
          if (res.success && res.data) {
            this.setState({ vno: res.data.vno, saveAreaId: res.data.areaId });
            this.handleModalVisible(true, false);
            const getFieldsList = form.getFieldsValue();
            Object.keys(res.data).forEach(key => {
              if (res.data[key]) {
                if (key === 'bankId') {
                  res.data[key] = `${res.data[key]}`;
                }
              }
            });
            Object.keys(getFieldsList).forEach(key => {
              if (res.data[key]) {
                if (key === 'bankId') {
                  form.setFieldsValue({ [key]: { key: res.data[key] } });
                } else {
                  form.setFieldsValue({ [key]: res.data[key] });
                }
              }
            });
          } else {
            message.warning(`${res.message || '暂无数据！'}`);
          }
        },
      });
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ loading: false, selectedRowKeys: [] });
  };

  // 新增修改提交数据
  submitData = () => {
    const { form, dispatch } = this.props;
    const { isAdd, suppId, saveAreaId, selectedRowKeys, nowPage, pageNum, vno } = this.state;
    let submitData = {};
    const submitType = isAdd
      ? 'suppliermaintenance/insertBankInfo'
      : 'suppliermaintenance/updateBankInfo';
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const tempValues = { ...values };
        const isAreaId = values.areaName.match(/^\d+$/);
        if (isAreaId) {
          tempValues.areaId = values.areaName;
        } else {
          tempValues.areaId = saveAreaId;
        }
        delete tempValues.areaName;
        Object.keys(tempValues).forEach(key => {
          if (tempValues[key] && tempValues[key].key) {
            tempValues[key] = tempValues[key].key;
          } else {
            tempValues[key] = tempValues[key] ? tempValues[key] : '';
          }
        });

        submitData = isAdd
          ? { suppId, ...tempValues }
          : { suppId, ...tempValues, bankAccoId: selectedRowKeys[0], vno };
        this.setState({ loading: true });
        dispatch({
          type: submitType,
          payload: submitData,
          callback: res => {
            this.setState({ loading: false, modalVisible: false });
            if (res.success) {
              message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
              this.getList(nowPage, pageNum);
              this.setState({ selectedRowKeys: [] });
            } else {
              message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
            }
          },
        });
      }
    });
  };

  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      bankList,
      areaList,
      fetching,
      nowPage,
      pageNum,
      cmTotal,
    } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.setState({ selectedRowKeys: selectedKeys });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };

    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: isAdd ? '新增银行账户信息' : '修改银行账户信息',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
    };
    // 下拉选项
    // 银行
    const bankOL = bankList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 地区
    const areaOL = areaList.map(options => (
      <Option key={options.areaId}>{options.areaName}</Option>
    ));
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.bankAccoId}
          loading={loading}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="城市">
              {getFieldDecorator('areaName', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select
                  placeholder="请输入地区关键字检索"
                  showSearch
                  showArrow={false}
                  filterOption={false}
                  onSearch={this.searchArea}
                  notFoundContent={fetching ? <Spin size="small" /> : null}
                >
                  {areaOL}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行">
              {getFieldDecorator('bankId', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  allowClear
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {bankOL}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户行">
              {getFieldDecorator('openBank', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行账号">
              {getFieldDecorator('bankAcco', {
                rules: [
                  { required: true, message: '最大长度不超过25位数字', pattern: /^\d{1,25}$/ },
                ],
              })(<Input placeholder="请输入" maxLength="25" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户单位名称">
              {getFieldDecorator('accoHolderName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请选择' }],
              })(<Input placeholder="请输入" maxLength="200" />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
